package com.sduept.nwld.dataserver.controller.fault;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSeparator;
import org.primefaces.model.menu.MenuModel;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.entity.FaultRecordAttachment;
import com.sduept.bigdata.fault.entity.FaultReportVersionLog;
import com.sduept.bigdata.fault.manager.FaultManager;
import com.sduept.bigdata.fault.manager.FaultRecordAttachmentManager;
import com.sduept.bigdata.fault.manager.FaultRecordPersistManager;
import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.bigdata.fault.manager.FaultReportQueryManager;
import com.sduept.bigdata.fault.manager.WaveFileAssistManager;
import com.sduept.bigdata.fault.report.doc.FaultReportVersionLogManager;
import com.sduept.bigdata.fault.report.doc.ProtectReportForLineFileManager;
import com.sduept.bigdata.fault.report.etl.factory.AnalysisModelFactoryBuilder;
import com.sduept.bigdata.fault.report.etl.model.DeviceActionDTO;
import com.sduept.bigdata.fault.report.etl.model.DeviceActionDetailDTO;
import com.sduept.bigdata.fault.report.etl.model.ProtectionActionAnalysisModel;
import com.sduept.bigdata.fault.report.etl.model.ProtectionActionTimeAnalysisModel;
import com.sduept.bigdata.weather.faultcause.manager.FaultCauseManager;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.cim.model.extend.AbstractWaveFile;
import com.sduept.cim.model.extend.LineSegment;
import com.sduept.cim.model.extend.LineTower;
import com.sduept.cim.model.extend.WaveFile;
import com.sduept.core.dao.SuperDAO;
import com.sduept.generator.ObjectId;
import com.sduept.kafka.service.exception.NoSuchTopicException;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.nwld.dataserver.manager.cim.LineTowerManager;
import com.sduept.nwld.dataserver.manager.etl.ProtectionDeviceActionETLManager;
import com.sduept.nwld.dataserver.manager.fault.FaultRecordAttachmentAssistManager;
import com.sduept.utils.DateUtil;
import com.sduept.utils.DecimalUtil;


@ViewScoped
@Named
public class LineFaultDetailsController extends ProtectActSvgController {

	private static final long serialVersionUID = -98017263590470607L;
	@Autowired
	private SuperDAO dao;
	@Autowired
	private MapDataCache cc;
	@Autowired
	private FaultManager frm;
	@Autowired
	private FaultRecordPersistManager frpm;
	@Autowired
	private LineTowerManager ltm;
	@Autowired
	private FaultCauseManager fcm;
	@Autowired
	private WaveFileAssistManager wfam;
	@Autowired
	private FaultReportQueryManager frqm;
	@Autowired
	private FaultRecordQueryManager queryManager;
	@Autowired
	private FaultReportVersionLogManager frvlManager;
	@Autowired
	private FaultRecordAttachmentManager attachManager;
	@Autowired
	private FaultRecordAttachmentAssistManager attachAssManager;
	@Autowired
	private ProtectReportForLineFileManager prfManager;
	@Autowired
	private ProtectionDeviceActionETLManager actionETLManager;
	@Autowired
	private CommonDocumentProperties pros;

	private ProtectionActionAnalysisModel pmodel;
	private List<DeviceActionDTO> firstActList = new ArrayList<DeviceActionDTO>();
	private List<DeviceActionDTO> secondActList = new ArrayList<DeviceActionDTO>();
	private List<DeviceActionDetailDTO> firstActDetailList = new ArrayList<DeviceActionDetailDTO>();
	private List<DeviceActionDetailDTO> secondActDetailList = new ArrayList<DeviceActionDetailDTO>();
	// 加上总出口的元件动作列表
	private List<DeviceActionDetailDTO> sumFirstActDetailList = new ArrayList<DeviceActionDetailDTO>();
	private List<DeviceActionDetailDTO> sumSecondActDetailList = new ArrayList<DeviceActionDetailDTO>();
	private ProtectionActionTimeAnalysisModel firstAction;
	private ProtectionActionTimeAnalysisModel secondAction;
	private StreamedContent file;
	private StreamedContent reportfile;
	private FaultReportVersionLog frvl;
	private FaultRecord record;
	private String showBackButton;
	private MenuModel firstWaveListModel;
	private MenuModel secondWaveListModel;
	private List<AbstractWaveFile> firstWaveList;
	private List<AbstractWaveFile> secondWaveList;
	// 非周期分量对应的list
	private List<Object[]> firstDecayingList;
	private List<Object[]> secondDecayingList;

	private boolean singleStation = false;

	public FaultReportVersionLog getFrvl() {
		return frvl;
	}

	public void setFrvl(FaultReportVersionLog frvl) {
		this.frvl = frvl;
	}

	private String actTimeList = null;// 时序图数据
	// 标识时序图数据是否取自于录波数据
	private boolean firstFileDataEffective = false;
	private boolean secondFileDataEffective = false;
	private String faultTime = null;
	private String deviceId = null;
	private String faultId = null;

	// 双端站
	private String startStation = null;
	private String endStation = null;
	private String startStationId = null;
	private String endStationId = null;

	private List<FaultRecordAttachment> attachmentList = new ArrayList<>();

	/**
	 * 初始化故障信息
	 *
	 * 将FaultRecord查询由使用SuperDAO改为使用 FaultRecordQueryManager查询 （20190109 zhangqi）
	 */
	@PostConstruct
	public void init() {
		if (StringUtils.isBlank(deviceId)) {
			deviceId = getParameter("lineId");
		}
		if (StringUtils.isBlank(showBackButton)) {
			showBackButton = getParameter("showBackButton");
		}
		if (StringUtils.isEmpty(deviceId)) {
			return;
		}
		if (faultTime == null) {
			faultTime = getParameter("faultTime");
		}
		Date dateTime = DateUtil.getDateByString(faultTime, DateUtil.pattern_ymdhms);
		List<FaultRecord> findByCondition = queryManager.findEqFaultTimeFaultByTimeDeviceId(dateTime, deviceId);
		if (findByCondition.size() > 0) {
			record = findByCondition.get(0);
			faultId = record.getId();
		}
		// 根据lineId获取双端站
		LineSegment acline = cc.getLineid_map().get(deviceId);
		if (acline != null) {
			startStation = acline.getStartStName();
			startStationId = acline.getStartST();
			endStation = acline.getEndStName();
			endStationId = acline.getEndST();
		}
		try {
			pmodel = AnalysisModelFactoryBuilder.getAnalysisModelFactory(AnalysisModelFactoryBuilder.xianlu)
					.makeAnalysisReport(deviceId, dateTime);// pa.getLineFaultAnalysisReport(deviceId,
			// dateTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		DecimalUtil.formatObjectDecimal(pmodel, 1);
		firstAction = pmodel.getFirstActions();
		secondAction = pmodel.getSecondActions();
		if (null != pmodel.getFirstSt()) {
			// 判断一下第一个站名是否和startStation是同一个,如果不是就换一下startSt和endSt
			if ((null != pmodel.getFirstSt().getSubstationName())
					&& (pmodel.getFirstSt().getSubstationName().equals(endStation))) {
				endStation = startStation;
				startStation = pmodel.getFirstSt().getSubstationName();
				String tmp = startStationId;
				startStationId = endStationId;
				endStationId = tmp;
			}
		}
		// 给动作元件列表添加总出口
		if (null != firstAction) {
			firstActDetailList = firstAction.getProtectionActionDetailList();
		}
		if (null != secondAction) {
			secondActDetailList = secondAction.getProtectionActionDetailList();
		}
		reloadSumActDetailList();

		// 组织时间序列图需要的数据
		if (null != pmodel.getFirstSt() && (isEffective(firstAction.getProtectionActionList())
				|| isEffective(firstAction.getBreakerActionList())
				|| isEffective(firstAction.getBreakerProtectionActionList()))) {
			// 第一个站的录波数据有效，时序图取录波数据
			firstFileDataEffective = true;
		}
		if (null != pmodel.getSecondSt() && (isEffective(secondAction.getProtectionActionList())
				|| isEffective(secondAction.getBreakerActionList())
				|| isEffective(secondAction.getBreakerProtectionActionList()))) {
			// 第一个站的录波数据有效，时序图取录波数据
			secondFileDataEffective = true;
		}

		actTimeList = getActTimeListStr();

		// 合并相别
		if (null != firstAction) {
			List<DeviceActionDTO> firstActionList = firstAction.getProtectionActionList();
			List<DeviceActionDTO> firstBreakerProtectActionList = firstAction.getBreakerProtectionActionList();
			if (null != firstActionList && firstActionList.size() > 0) {
				firstActList = combinePhase(firstActionList);
			}
			if (null != firstBreakerProtectActionList && firstBreakerProtectActionList.size() > 0) {
				firstActList.addAll(combinePhase(firstBreakerProtectActionList));
			}
		}
		if (null != secondAction) {
			List<DeviceActionDTO> secondActionList = secondAction.getProtectionActionList();
			List<DeviceActionDTO> secondBreakerProtectActionList = secondAction.getBreakerProtectionActionList();
			if (null != secondActionList && secondActionList.size() > 0) {
				secondActList = combinePhase(secondActionList);
			}
			if (null != secondBreakerProtectActionList && secondBreakerProtectActionList.size() > 0) {
				secondActList.addAll(combinePhase(secondBreakerProtectActionList));
			}
		}

		// 生成录波文件列表
		generateWaveFileList(record);
		initDecayingList();
		singleStation = pmodel.getSecondSt() == null;
		// 初始化附件图片
		attachmentList = attachManager.findByFaultId(faultId);
	}

	public void generateWaveFileList(FaultRecord fault) {
		if (pmodel.getFirstSt() != null) {
			firstWaveList = wfam.findWaveFileList(fault, fault.getStationId());
			firstWaveListModel = loadWaveListMenu(firstWaveList, 1);
		}
		if (pmodel.getSecondSt() != null) {
			secondWaveList = wfam.findWaveFileList(fault, fault.getStationId2());
			secondWaveListModel = loadWaveListMenu(secondWaveList, 2);
		}
	}

	private void initDecayingList() {
		if (pmodel.getFirstSt() != null) {
			Object[] fa = new Object[] { "A", pmodel.getFirstSt().getAphaseDecayingDCcomponent(),
					pmodel.getFirstSt().getAphaseAttenuationConstant() };
			Object[] fb = new Object[] { "B", pmodel.getFirstSt().getBphaseDecayingDCcomponent(),
					pmodel.getFirstSt().getBphaseAttenuationConstant() };
			Object[] fc = new Object[] { "C", pmodel.getFirstSt().getCphaseDecayingDCcomponent(),
					pmodel.getFirstSt().getCphaseAttenuationConstant() };
			firstDecayingList = Arrays.asList(fa, fb, fc);
		}
		if (pmodel.getSecondSt() != null) {
			Object[] sa = new Object[] { "A", pmodel.getSecondSt().getAphaseDecayingDCcomponent(),
					pmodel.getSecondSt().getAphaseAttenuationConstant() };
			Object[] sb = new Object[] { "B", pmodel.getSecondSt().getBphaseDecayingDCcomponent(),
					pmodel.getSecondSt().getBphaseAttenuationConstant() };
			Object[] sc = new Object[] { "C", pmodel.getSecondSt().getCphaseDecayingDCcomponent(),
					pmodel.getSecondSt().getCphaseAttenuationConstant() };
			secondDecayingList = Arrays.asList(sa, sb, sc);
		}
	}

	private MenuModel loadWaveListMenu(List<AbstractWaveFile> waveList, Integer type) {
		MenuModel waveListModel = new DefaultMenuModel();
		if (waveList.size() == 0) {
			DefaultMenuItem item = new DefaultMenuItem();
			item.setValue("无录波文件");
			waveListModel.addElement(item);
		} else {
			for (AbstractWaveFile w : waveList) {
				DefaultMenuItem item = new DefaultMenuItem();
				item.setIcon("ui-icon-folder-open");
				if (w instanceof WaveFile) {
					item.setValue("集中录波");
				} else {
					item.setValue(w.getEquipType());
				}
				if (type - 1 == 0) {
					item.setOnclick("openWaveDlg('" + w.getId() + "','" + startStationId + "','" + startStation + "')");
				} else {
					item.setOnclick("openWaveDlg('" + w.getId() + "','" + endStationId + "','" + endStation + "')");
				}
				waveListModel.addElement(item);
			}
			DefaultMenuItem item = new DefaultMenuItem();
			item.setIcon("ui-icon-arrowthick-1-s");
			item.setValue("下载全部录波文件");
			item.setUpdate("file");
			if (type - 1 == 0) {
				item.setOncomplete("document.getElementById('firstSt:file').click();");
			} else {
				item.setOncomplete("document.getElementById('secondSt:file').click();");
			}
			waveListModel.addElement(item);
		}
		waveListModel.addElement(new DefaultSeparator());
		DefaultMenuItem item = new DefaultMenuItem();
		item.setIcon("ui-icon-grip-dotted-vertical");
		item.setValue("查看故障特征");
		if (type - 1 == 0) {
			item.setOnclick("openHarDlg('" + pmodel.getFirstSt().getFaultFileId() + "')");
		} else {
			item.setOnclick("openHarDlg('" + pmodel.getSecondSt().getFaultFileId() + "')");
		}
		waveListModel.addElement(item);
		return waveListModel;
	}

	// 每个站先判断录波，没有录波的取动作元件
	private String getActTimeListStr() {
		JSONArray jsonArray = new JSONArray();
		com.alibaba.fastjson.JSONObject firstJso = null;
		com.alibaba.fastjson.JSONObject secondJso = null;
		if (!firstFileDataEffective) {
			if (firstActDetailList.size() > 0) {
				// 如果没有录波文件的话,取动作元件的时间列表
				firstJso = getActListByComponent(pmodel.getFirstSt().getSubstationName(), firstActDetailList);
			}
		} else {
			// 如果有录波文件
			firstJso = getActTimeListByRecorder(pmodel.getFirstSt().getSubstationName(), firstAction);
		}
		if (null != firstJso) {
			jsonArray.add(firstJso);
		}
		if (!secondFileDataEffective) {
			if (secondActDetailList.size() > 0) {
				secondJso = getActListByComponent(pmodel.getSecondSt().getSubstationName(), secondActDetailList);
			}
		} else {
			// 如果有录波文件
			secondJso = getActTimeListByRecorder(pmodel.getSecondSt().getSubstationName(), secondAction);
		}
		if (null != secondJso) {
			jsonArray.add(secondJso);
		}
		return jsonArray.toJSONString();
	}

	// 重新预测故障原因
	public void forecast() {
		List<FaultRecord> frs = queryManager.findEqFaultTimeFaultByTimeDeviceId(pmodel.getFaultTime(),
				pmodel.getFaultLineId());
		if (frs.size() > 0) {
			FaultRecord fr = frs.get(0);
			frm.setupFaultForecastReasonClassify(fr, pmodel);
			pmodel.setFaultForecastReason(fr.getFaultForecastReson());
		}
	}

	// 重新获取录波文件
	public void getWaveFile() {
		if (null != record && StringUtils.isNotEmpty(faultTime)) {
			try {
				frm.regetWaveAndParse(faultTime, record.getId());
			} catch (NoSuchTopicException e) {
				e.printStackTrace();
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}

	public void reloadActionData() {
		actionETLManager.getAndSaveActionData(record);
		frqm.reloadDeviceDetailActionDTO(record.getId(), pmodel);
		firstActDetailList = pmodel.getFirstActions().getProtectionActionDetailList();
		secondActDetailList = pmodel.getSecondActions().getProtectionActionDetailList();
		reloadSumActDetailList();
		if (firstActDetailList.size() > 0 || secondActDetailList.size() > 0) {
			actTimeList = getActTimeListStr();
		}
	}

	private void reloadSumActDetailList() {
		sumFirstActDetailList.clear();
		if (firstActDetailList != null && firstActDetailList.size() > 0) {
			sumFirstActDetailList.addAll(firstActDetailList);
			if (pmodel.getFirstSt() != null) {
				DeviceActionDetailDTO sum1 = new DeviceActionDetailDTO();
				sum1.setProtectName("总出口");
				sum1.setProtectType(pmodel.getFirstSt().getTotalExportCount() + "次");
				sumFirstActDetailList.add(sum1);
			}
		}
		sumSecondActDetailList.clear();
		if (secondActDetailList != null && secondActDetailList.size() > 0) {
			sumSecondActDetailList.addAll(secondActDetailList);
			if (pmodel.getSecondSt() != null) {
				DeviceActionDetailDTO sum2 = new DeviceActionDetailDTO();
				sum2.setProtectName("总出口");
				sum2.setProtectType(pmodel.getSecondSt().getTotalExportCount() + "次");
				sumSecondActDetailList.add(sum2);
			}
		}
	}

	// 元件列表索引
	public int getIndex(DeviceActionDetailDTO dto, int num) {
		if (num == 1) {
			return firstActDetailList.indexOf(dto) + 1;
		} else {
			return secondActDetailList.indexOf(dto) + 1;
		}
	}

	// 保护动作时间列表中，相同的保护相同动作，时间相差在5ms以内的合并相别
	private List<DeviceActionDTO> combinePhase(List<DeviceActionDTO> actList) {
		List<DeviceActionDTO> newActList = new ArrayList<DeviceActionDTO>();
		outer: for (DeviceActionDTO d : actList) {
			DeviceActionDTO dc = null;
			try {
				dc = d.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
			if (null != dc) {
				String actName = getActType(dc.getJump_remark());
				dc.setJump_remark(actName);
				for (DeviceActionDTO dto : newActList) {
					if (dc.getDistance_0_moments_time() >= dto.getDistance_0_moments_time() - 5000
							&& dc.getDistance_0_moments_time() <= dto.getDistance_0_moments_time() + 5000
							&& dc.getDevice_id().equals(dto.getDevice_id()) && dto.getJump_remark().equals(actName)) {
						dto.setPhase(dto.getPhase() + dc.getPhase());
						continue outer;
					}
				}
				newActList.add(dc);
			}
		}
		for (DeviceActionDTO da : newActList) {
			char[] phase = da.getPhase().toCharArray();
			Arrays.sort(phase);
			da.setPhase(String.valueOf(phase));
		}
		// 按时间排序
		Collections.sort(newActList, new Comparator<DeviceActionDTO>() {
			@Override
			public int compare(DeviceActionDTO o1, DeviceActionDTO o2) {
				return o1.getDistance_0_moments_time() - o2.getDistance_0_moments_time();
			}

		});
		return newActList;
	}

	// 重新生成故障报告，保存到数据库，并下载到本地
	public void refreshReport() {
		try {
			Date _faultTime = DateUtil.getDateByString(faultTime, DateUtil.pattern_ymdhms);
			FaultReportVersionLog frvlLastest = new FaultReportVersionLog();
			List<FaultReportVersionLog> frvlLastests = frvlManager.findByCondition(deviceId, _faultTime);
			if (frvlLastests != null && !frvlLastests.isEmpty()) {
				frvlLastest = frvlLastests.get(0);
				frvlLastest.setLastest(false);
				frvlManager.updateFaultReportVersionLog(frvlLastest);
			}
			createFaultReport(deviceId, _faultTime, frvlLastest);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 下载故障报告
	public void downLoadReport() {
		try {
			Date _faultTime = DateUtil.getDateByString(faultTime, DateUtil.pattern_ymdhms);
			List<FaultReportVersionLog> frvls = frvlManager.findByCondition(deviceId, _faultTime);
			if (frvls != null && !frvls.isEmpty()) {
				for (FaultReportVersionLog frvl : frvls) {
					if (frvl.isLastest()) {
						downloadFaultReport(frvl);
						break;
					}
				}
			} else {
				createFaultReport(deviceId, _faultTime, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 本地上传故障报告文件
	public void handleFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String suffix = file.getFileName().substring(file.getFileName().lastIndexOf("."));
		String id = ObjectId.get().toString();
		String dirFileName = id + suffix;
		String path = pros.getDocumentPath() + dirFileName;
		try {
			FileOutputStream fos = new FileOutputStream(path);
			fos.write(file.getContents());
			fos.close();
			if (pmodel != null) {
				FaultReportVersionLog frvlLastest = null;
				// and faultTime='"+pmodel.getFaultTime()+"'
				List<FaultReportVersionLog> frvlLastests = dao.findByCondition("isLastest=true and faultLineId=?",
						new Object[] { pmodel.getFaultLineId() }, FaultReportVersionLog.class);
				if (frvlLastests != null && !frvlLastests.isEmpty()) {
					frvlLastest = frvlLastests.get(0);
					frvlLastest.setLastest(false);
					frvlManager.updateFaultReportVersionLog(frvlLastest);
				}
				frvl = new FaultReportVersionLog();
				frvl.setFaultLineId(pmodel.getFaultLineId());
				frvl.setFaultTime(pmodel.getFaultTime());
				frvl.setFaultType(pmodel.getFaultType());
				frvl.setReportFilePath(pros.getDocumentPath() + dirFileName);
				frvl.setReportName(pmodel.getFaultLineId() + pmodel.getFaultTime().getTime() + ".doc");
				frvl.setLastest(true);
				if (frvlLastest != null)
					frvl.setReportVersion(frvlLastest.getReportVersion() + 1);
				else
					frvl.setReportVersion(1.0f);
				frvl.setName("reEditGenerate");
				frvl.setUploadPerson(getCurrentUser().getName());
				frvl.setUploadTime(new Date());
				frvl = frvlManager.createFaultReportVersionLog(frvl);
				addSuccessMessage("文件上传成功");
			}
		} catch (IOException ee) {
			ee.printStackTrace();
			addErrorMessage("待导入文件上传失败");
		}
	}

	private void createFaultReport(String faultLineId, Date faultTime, FaultReportVersionLog frvlLastest) {
		try {
			ProtectionActionAnalysisModel model = AnalysisModelFactoryBuilder
					.getAnalysisModelFactory(AnalysisModelFactoryBuilder.xianlu)
					.makeWordAnalysisReport(deviceId, faultTime);// pa.getLineFaultAnalysisReport(deviceId,
			// dateTime);
			// pa.getLineFaultAnalysisReport(faultLineId, faultTime);
			if (model.getFirstSt() == null) {
				addErrorMessage("未找到该故障发生的初始站信息");
				return;
			}
			boolean flag = prfManager.generateProtectReportFileContext(
					pros.getTempletePath() + "lineFaultAnalysisModel.docx", model);
			if (flag) {
				frvl = new FaultReportVersionLog();
				frvl.setFaultLineId(model.getFaultLineId());
				frvl.setFaultTime(model.getFaultTime());
				frvl.setFaultType(model.getFaultType());
				frvl.setReportFilePath(pros.getDocumentPath() + model.getFaultLineId() + "_"
						+ model.getFaultTime().getTime() + ".doc");
				frvl.setReportName(model.getFaultLineId() + model.getFaultTime().getTime() + ".doc");
				frvl.setLastest(true);
				if (frvlLastest == null)
					frvl.setReportVersion(1.0f);
				else
					frvl.setReportVersion(frvlLastest.getReportVersion() + 1);
				frvl.setName("SystemAutoGenerate");
				frvl.setUploadPerson(getCurrentUser().getName());
				frvl.setUploadTime(new Date());
				frvl = frvlManager.createFaultReportVersionLog(frvl);
			}
			if (frvl != null) {
				addSuccessMessage("故障分析报告成功生成！");// why no show？
				downloadFaultReport(frvl);
			}
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("故障分析报告生成异常!");
		}
	}

	private void downloadFaultReport(FaultReportVersionLog frvl) {
		try {
			File f1 = new File(frvl.getReportFilePath());
			InputStream stream = new FileInputStream(
					new File(pros.getDocumentPath() + new String(f1.getName().getBytes(), "UTF-8")));
			reportfile = new DefaultStreamedContent(stream, "application/octet-stream", f1.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 训练
	public void train() {
		Double[] location = getFaultLocation();
		String[] s = new String[6];
		s[0] = pmodel.getFaultLineId();
		// s[1] = DateUtil.getStringDate(pmodel.getFaultTime(),
		// DateUtil.pattern_ymdhms);
		s[2] = location[0] + "";
		s[3] = location[1] + "";
		s[4] = "10";
		s[5] = "0,1";
		if (StringUtils.isEmpty(s[0])) {
			addErrorMessage("线路Id为空");
		} else if (StringUtils.isEmpty(s[1])) {
			addErrorMessage("故障时间为空");
		} else if (StringUtils.isEmpty(s[2])) {
			addErrorMessage("经度为空");
		} else if (StringUtils.isEmpty(s[3])) {
			addErrorMessage("纬度为空");
		} else {
			// 更新CimFault
			FaultRecord record = frm.getFaultByDeviceIdAndTime(s[0], pmodel.getFaultTime());
			if (record != null) {
				record.setFaultReson(pmodel.getFaultReason());
				frpm.saveFaultRecordOnly(record);
			}
			//TODO:用新的模型训练放放
//			fcm.modelTraining(modelType, svmdatas);
			addSuccessMessage("训练成功");
		}

	}

	// 下载录波文件
	public void downLoadFile(String index) {
		List<AbstractWaveFile> files;
		String stationId;
		if ("1".equals(index)) {
			files = firstWaveList;
			stationId = startStationId;
		} else {
			files = secondWaveList;
			stationId = endStationId;
		}
		file = null;
		if (files.size() > 0) {
			FileInputStream fis = null;
			try {
				fis = wfam.generateDownloadZipFile(record, stationId);
				file = new DefaultStreamedContent(fis, "application/octet-stream",record.getEquipment() + ".zip") ;
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
		if (file == null) {
			addErrorMessage("查找文件失败，无法下载");
		}
	}

	public void downloadAttachment() {
		if (attachmentList != null && attachmentList.size() > 0) {
			file = attachAssManager.getAttachmentFile(attachmentList);
			if (file == null) {
				addErrorMessage("该文件不存在");
			}
		}
	}

	public Double[] getFaultLocation() {
		Double[] d = new Double[2];
		LineSegment acline = cc.getLineid_map().get(pmodel.getFaultLineId());
		Double startCalcJuli = null;// 故障距离起始站距离 通过起始站计算得出
		Double endSCalcJuli = null;// 故障距离起始站距离 通过终点站计算得出
		if (pmodel.getFirstSt() != null) {
			if (pmodel.getFirstSt().getSubstaionId().equals(acline.getStartST()))
				startCalcJuli = pmodel.getFirstSt().getRangingWave();// 拿到录波测距
			else {
				if (pmodel.getFirstSt().getRangingWave() != null)
					endSCalcJuli = acline.getLength() - pmodel.getFirstSt().getRangingWave();// 拿到录波测距
			}
		}
		if (pmodel.getSecondSt() != null) {
			if (pmodel.getSecondSt().getSubstaionId().equals(acline.getStartST()))
				startCalcJuli = pmodel.getSecondSt().getRangingWave();// 拿到录波测距
			else {
				if (pmodel.getSecondSt().getRangingWave() != null)
					endSCalcJuli = acline.getLength() - pmodel.getSecondSt().getRangingWave();// 拿到录波测距
			}
		}
		LineTower lt = null;
		if (startCalcJuli != null)
			lt = ltm.getShortestLinetower(pmodel.getFaultLineId(), startCalcJuli);
		else if (endSCalcJuli != null)
			lt = ltm.getShortestLinetower(pmodel.getFaultLineId(), endSCalcJuli);
		if (lt != null) {
			d[0] = lt.getLongitude();// 精度
			d[1] = lt.getLatitude();// 维度
		}
		return d;
	}

	public String replaceWithBr(String str) {
		if (StringUtils.isEmpty(str)) {
			str = "";
		} else {
			str = str.replaceAll("(\r\n|\r|\n|\n\r)", "<br/>");
		}
		return str;
	}

	public boolean isPicture(FaultRecordAttachment m) {
		return attachAssManager.isPicture(m.getSuffix());
	}

	public String getVirtualPath(String path) {
		return attachAssManager.getFullPath(path);
	}

	public ProtectionActionAnalysisModel getPmodel() {
		return pmodel;
	}

	public void setPmodel(ProtectionActionAnalysisModel pmodel) {
		this.pmodel = pmodel;
	}

	public List<DeviceActionDTO> getFirstActList() {
		return firstActList;
	}

	public void setFirstActList(List<DeviceActionDTO> firstActList) {
		this.firstActList = firstActList;
	}

	public List<DeviceActionDTO> getSecondActList() {
		return secondActList;
	}

	public void setSecondActList(List<DeviceActionDTO> secondActList) {
		this.secondActList = secondActList;
	}

	public ProtectionActionTimeAnalysisModel getSecondAction() {
		return secondAction;
	}

	public void setSecondAction(ProtectionActionTimeAnalysisModel secondAction) {
		this.secondAction = secondAction;
	}

	public ProtectionActionTimeAnalysisModel getFirstAction() {
		return firstAction;
	}

	public void setFirstAction(ProtectionActionTimeAnalysisModel firstAction) {
		this.firstAction = firstAction;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public String getActTimeList() {
		return actTimeList;
	}

	public void setActTimeList(String actTimeList) {
		this.actTimeList = actTimeList;
	}

	public List<DeviceActionDetailDTO> getSumFirstActDetailList() {
		return sumFirstActDetailList;
	}

	public void setSumFirstActDetailList(List<DeviceActionDetailDTO> sumFirstActDetailList) {
		this.sumFirstActDetailList = sumFirstActDetailList;
	}

	public List<DeviceActionDetailDTO> getSumSecondActDetailList() {
		return sumSecondActDetailList;
	}

	public void setSumSecondActDetailList(List<DeviceActionDetailDTO> sumSecondActDetailList) {
		this.sumSecondActDetailList = sumSecondActDetailList;
	}

	public StreamedContent getReportfile() {
		return reportfile;
	}

	public void setReportfile(StreamedContent reportfile) {
		this.reportfile = reportfile;
	}

	public String getStartStation() {
		return startStation;
	}

	public void setStartStation(String startStation) {
		this.startStation = startStation;
	}

	public String getEndStation() {
		return endStation;
	}

	public void setEndStation(String endStation) {
		this.endStation = endStation;
	}

	public String getDeviceId() {
		return deviceId;
	}

	public void setDeviceId(String deviceId) {
		this.deviceId = deviceId;
	}

	public String getShowBackButton() {
		return showBackButton;
	}

	public void setShowBackButton(String showBackButton) {
		this.showBackButton = showBackButton;
	}

	public MenuModel getFirstWaveListModel() {
		return firstWaveListModel;
	}

	public void setFirstWaveListModel(MenuModel firstWaveListModel) {
		this.firstWaveListModel = firstWaveListModel;
	}

	public MenuModel getSecondWaveListModel() {
		return secondWaveListModel;
	}

	public void setSecondWaveListModel(MenuModel secondWaveListModel) {
		this.secondWaveListModel = secondWaveListModel;
	}

	public List<Object[]> getFirstDecayingList() {
		return firstDecayingList;
	}

	public void setFirstDecayingList(List<Object[]> firstDecayingList) {
		this.firstDecayingList = firstDecayingList;
	}

	public List<Object[]> getSecondDecayingList() {
		return secondDecayingList;
	}

	public void setSecondDecayingList(List<Object[]> secondDecayingList) {
		this.secondDecayingList = secondDecayingList;
	}

	public boolean isSingleStation() {
		return singleStation;
	}

	public void setSingleStation(boolean singleStation) {
		this.singleStation = singleStation;
	}

	public String getFaultId() {
		return faultId;
	}

	public void setFaultId(String faultId) {
		this.faultId = faultId;
	}

	public List<FaultRecordAttachment> getAttachmentList() {
		return attachmentList;
	}

	public void setAttachmentList(List<FaultRecordAttachment> attachmentList) {
		this.attachmentList = attachmentList;
	}

	public FaultRecord getRecord() {
		return record;
	}

	public void setRecord(FaultRecord record) {
		this.record = record;
	}

}
